package com.gin.no_gay_alliance.manager;

import android.content.Context;
import android.view.LayoutInflater;

import androidx.annotation.NonNull;
import androidx.viewbinding.ViewBinding;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;

/**
 * ViewBinding管理器，使用反射对单例模式运行的ViewBinding对象进行统一管理
 *
 * @author : ginstone
 * @version : v1.0.0
 * @since : 2023/9/8 11:24
 **/
public class ViewBindingManager {
    /**
     * 缓存对象
     */
    private final HashMap<Class<? extends ViewBinding>, Object> cache = new HashMap<>();

    /**
     * 通过反射调用 ViewBinding 的 inflate 方法对布局进行渲染
     *
     * @param clazz   ViewBinding类对象
     * @param context 上下文
     * @param <T>     ViewBinding类
     * @return ViewBinding对象
     */
    public <T extends ViewBinding> T getDialogView(@NonNull Class<T> clazz, @NonNull Context context) {
        Object o = cache.get(clazz);
        if (o != null) {
            return (T) o;
        }
        try {
            Method method = clazz.getMethod("inflate", LayoutInflater.class);
            T b = (T) method.invoke(clazz, LayoutInflater.from(context));
            cache.put(clazz, b);
            return b;
        } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
            e.printStackTrace();
            return null;
        }
    }
}
